package router

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"wwgin/controller/api"
)

//中间键 允许跨域
func Origin() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Headers", "Access-Control-Allow-Headers,Authorization,User-Agent, Keep-Alive, Content-Type, X-Requested-With,X-CSRF-Token,AccessToken,Token")
		c.Header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, PATCH, OPTIONS")
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		c.Header("Access-Control-Allow-Credentials", "true")
		// 放行所有OPTIONS请求
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusAccepted)
		}
		c.Next()
	}
}

//api模块的路由
func InitApiRouter(r *gin.Engine) {
	group := r.Group("/api").Use(Origin()) //使用中间键验证参数
	{
		group.GET("/getinfo", (&api.Ip{}).GetInfo)
		group.GET("/getinfos", (&api.Ip{}).GetInfos)
	}
	group1 := r.Group("/index").Use(Origin()) //使用中间键验证参数
	{
		group1.GET("/index", (&api.Index{}).Index)
		group1.GET("/add", (&api.Index{}).Add)
		group1.GET("/info", (&api.Index{}).Info)
	}
}
